////////////////////////////////////////////////
//
// Author: Arkadiusz Kiciak (WITS)
// City: Gdansk POLAND
// Date: 18 May 2014
// License: GPLV3
//
////////////////////////////////////////////////
//
// Feel free to redistributing this code but never
// forget to add original place where you found this
// Thanks!!!
//
////////////////////////////////////////////////

#include <avr/interrupt.h>
#include <avr/io.h>
#include <stdint.h>

#include "commonProcs.h"
#include "keyConfig.h"

#define player1Input				PIND
#define player1Pin	 				PD5
#define player1Dir					DDRD
#define checkPlayer1 \
	!(player1Input & ( 1 << player1Pin))

#define player2Input				PIND
#define player2Pin		 			PD6
#define player2Dir					DDRD
#define checkPlayer2 \
	!(player2Input & ( 1 << player2Pin))

extern volatile uint32_t player1Time;
extern volatile uint32_t player2Time;

extern volatile uint8_t player1TimeCounting;
extern volatile uint8_t player2TimeCounting;

extern uint32_t maxTime;

extern volatile uint8_t gameOver;

uint8_t player1Pressed = 0;
uint8_t player2Pressed = 0;

void keyInit(void) {

	clrBitAt(player1Dir,player1Pin);
	
	clrBitAt(player2Dir,player2Pin);

	timer0Init();

}

void timer0Init(void) {

	//mode normal
	clrBitAt(TCCR0,WGM00);
	clrBitAt(TCCR0,WGM01);

	//normal port operation, oc0 disconnected
	clrBitAt(TCCR0,COM00);
	clrBitAt(TCCR0,COM01);
	
	//prescaler /256
	setBitAt(TCCR0,CS02);
	clrBitAt(TCCR0,CS01);
	clrBitAt(TCCR0,CS00);
	
	TCNT0 = 0;
	
	//allowed to interrupt at overflow
	setBitAt(TIMSK,TOIE0);
	
}

ISR (TIMER0_OVF_vect){

	static uint8_t player1History = 0;
	static uint8_t player2History = 0;
	 
	player1History <<= 1;
	player2History <<= 1;
	
	setBitDependOf(checkPlayer1,player1History,0);
	setBitDependOf(checkPlayer2,player2History,0);
	
	if(player1History == 0x7F){
		
		player1Pressed = 1;
		
	}
	
	if(player2History == 0x7F){
		
		player2Pressed = 1;
		
	}
	
	if(player1TimeCounting){
	
		if(!player1Pressed)
		
			player1Time++;
		
		else
		
			player1TimeCounting = 0;
			
	}
	
	if(player2TimeCounting){
	
		if(!player2Pressed)
		
			player2Time++;
		
		else
		
			player2TimeCounting = 0;
			
	}
	
	//check gameover cond terms
	if(!player1TimeCounting && !player2TimeCounting && !gameOver){
	
		gameOver = 1;
		
		return;
	
	}
	
	//no respond of player1
	if((player1Time > maxTime ) && player1TimeCounting){
	
		player1TimeCounting = 0;
		
		gameOver = 1;
		
		return;
		
	}

	//no respond of player2
	if((player2Time > maxTime ) && player2TimeCounting){
	
		player2TimeCounting = 0;
		
		gameOver = 1;
	
	}
	
}
